<template>
  <view class="container">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">系统通知</text>
    </view>
    
    <!-- 空状态提示 -->
    <view v-if="notifications.length === 0" class="empty-state">
      <image src="/static/images/empty-notification.png" mode="widthFix" class="empty-img"></image>
      <text class="empty-text">暂无通知消息</text>
    </view>

    <!-- 通知列表 -->
    <view v-else class="message-list">
      <view class="message-item" v-for="(item, index) in notifications" :key="item.messageId"
        @tap="handleNotificationTap(item)">
        <image :src="item.avatarUrl || '/static/images/default-avatar.png'" mode="aspectFill" class="message-avatar"></image>
        <view class="message-info">
          <view class="message-header">
            <text class="message-title">{{ item.nickName || '系统通知' }}</text>
            <text class="message-time">{{ formatTime(item.sendTime) }}</text>
          </view>
          <text class="message-desc line-clamp-1">{{ item.content || '暂无内容' }}</text>
        </view>
        <!-- 未读红点（如果接口有unread字段可启用） -->
        <!-- <view v-if="item.unread" class="unread-dot"></view> -->
      </view>
    </view>
  </view>
</template>

<script>
import { ref, onMounted } from 'vue'
import { getMessageRemindingByreceiverId } from '@/api/post.js';
import userManager from '@/common/utils/user.js'
import messageCenter from '@/common/utils/messagecenter.js'
import TimeUtil from '@/common/utils/time.js'

export default {
  setup() {
    const notifications = ref([])

    // 格式化时间显示（适配接口返回的sendTime格式）
    const formatTime = (timeStr) => {
      if (!timeStr) return ''
      // 假设接口返回的是类似"2023-10-01 12:30:45"的格式
      const date = new Date(timeStr)
      // 检查日期是否有效
      if (isNaN(date.getTime())) return ''
      
      const now = new Date()
      const diff = now - date
      
      // 如果是今天，显示时:分
      if (date.toDateString() === now.toDateString()) {
        return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
      }
      
      // 如果是昨天，显示昨天
      const yesterday = new Date(now)
      yesterday.setDate(yesterday.getDate() - 1)
      if (date.toDateString() === yesterday.toDateString()) {
        return '昨天'
      }
      
      // 如果是一周内，显示星期几
      if (diff < 7 * 24 * 60 * 60 * 1000) {
        const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
        return weekdays[date.getDay()]
      }
      
      // 其他情况显示月/日
      return `${date.getMonth() + 1}/${date.getDate()}`
    }

    // 处理通知点击事件
    const handleNotificationTap = (item) => {
      // 检查是否是好友申请相关的通知
      if (item.action === 'friend_request' || 
          item.action === 'friend_accepted' || 
          item.action === 'friend_rejected') {
        // 清除该消息的未读状态
        clearNotificationUnread(item)
        
        // 跳转到好友申请页面
        uni.navigateTo({
          url: '/pages/friend-requests/friend-requests'
        })
        return
      }
      
      // 其他类型的通知跳转到帖子详情
      if (!item.postId) {
        uni.showToast({
          title: '缺少文章ID',
          icon: 'none'
        })
        return
      }
      uni.navigateTo({
        url: `/pages/post-detail/post-detail?id=${item.postId}`
      })
    }
    
    // 清除通知的未读状态
    const clearNotificationUnread = (item) => {
      // 找到对应的聊天记录并标记为已读
      const chat = messageCenter.chatList.find(c => 
        c.id === item.fromId && c.chatType === 'notification'
      )
      
      if (chat) {
        // 标记所有消息为已读
        chat.readNum = chat.list.length
        chat.readTime = TimeUtil.now ? TimeUtil.now() : new Date().toLocaleString()
        
        // 更新到 messageCenter（会触发未读数量重新计算和TabBar徽章更新）
        messageCenter.setReadTime(chat)
      }
      
      // 更新TabBar徽章
      setTimeout(() => {
        messageCenter.calculateUnreadCounts(true)
      }, 100)
    }

    // 获取通知数据（核心修正点）
    const fetchNotifications = async () => {
      try {
        console.log('开始请求通知数据')
        const res = await getMessageRemindingByreceiverId()
        console.log('接口返回数据:', res)

        // 关键修正：接口直接返回数组，无需解析res.data
        if (Array.isArray(res)) {
          notifications.value = res
          console.log('通知列表赋值成功，长度：', notifications.value.length)
        } else {
          notifications.value = []
          uni.showToast({
            title: '数据格式错误',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取通知失败:', error)
        notifications.value = []
        uni.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        })
      }
    }

    onMounted(() => {
      fetchNotifications()
      
      // 清除所有互动消息相关的未读消息
      const notificationChats = messageCenter.chatList.filter(c => 
        c.chatType === 'notification' && 
        c.user &&
        // 如果没有action字段或者action字段不是好友申请相关的，则认为是互动消息
        (!c.user.action || 
          !(c.user.action === 'friend_request' || 
            c.user.action === 'friend_accepted' || 
            c.user.action === 'friend_rejected'))
      )
      
      console.log('提醒页面 - 找到的互动消息聊天:', notificationChats)
      
      notificationChats.forEach(chat => {
        // 标记所有消息为已读
        chat.readNum = chat.list.length
        chat.readTime = TimeUtil.now ? TimeUtil.now() : new Date().toLocaleString()
        messageCenter.setReadTime(chat)
      })
      
      // 更新TabBar徽章
      setTimeout(() => {
        messageCenter.calculateUnreadCounts(true)
      }, 100)
    })

    return {
      notifications,
      handleNotificationTap,
      formatTime
    }
  }
}
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.page-header {
  background-color: #fff;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 300rpx;
}

.empty-img {
  width: 200rpx;
  margin-bottom: 40rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #999;
}

/* 列表样式 */
.message-list {
  background-color: #f5f5f5;
  padding: 20rpx;
}

.message-item {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.message-avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  margin-right: 24rpx;
  background-color: #eee; /* 占位背景 */
}

.message-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-height: 100rpx;
  overflow: hidden;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}

.message-title {
  font-size: 34rpx;
  font-weight: 600;
  color: #333;
  max-width: 400rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.message-time {
  font-size: 26rpx;
  color: #999;
}

.message-desc {
  font-size: 30rpx;
  color: #666;
  line-height: 1.4;
}

/* 未读消息红点 */
.unread-dot {
  width: 24rpx;
  height: 24rpx;
  border-radius: 50%;
  background-color: #ff4d4f;
  margin-left: 16rpx;
}

/* 点击反馈 */
.message-item:active {
  background-color: #f9f9f9;
}
</style>